package com.sq.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sq.shortlink.admin.common.biz.user.UserContext;
import com.sq.shortlink.admin.common.convension.exception.ClientException;
import com.sq.shortlink.admin.dao.entity.UserDO;
import com.sq.shortlink.admin.dao.mapper.UserMapper;
import com.sq.shortlink.admin.dto.req.UserLoginReqDTO;
import com.sq.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.sq.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.sq.shortlink.admin.dto.resp.UserActualRepDTO;
import com.sq.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.sq.shortlink.admin.dto.resp.UserRepDTO;
import com.sq.shortlink.admin.service.GroupService;
import com.sq.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.sq.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.sq.shortlink.admin.common.convension.errorcode.BaseErrorCode.*;
import static com.sq.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * 用户接口实现层
 * @author quan
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;
    @Override
    public UserActualRepDTO getActualUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<UserDO>();
        wrapper.eq(UserDO::getUsername,username);
        UserDO userDO = getOne(wrapper);
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }
        return BeanUtil.toBean(userDO,UserActualRepDTO.class);
    }

    @Override
    public UserRepDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<UserDO>();
        wrapper.eq(UserDO::getUsername,username);
        UserDO userDO = getOne(wrapper);
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }
        return BeanUtil.toBean(userDO,UserRepDTO.class);
    }

    @Override
    public Boolean hasUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(!hasUsername(requestParam.getUsername())){
            throw new ClientException(USER_NAME_EXIST_ERROR);
        }
        RLock rLock = redissonClient.getLock(LOCK_USER_REGISTER_KEY +requestParam.getUsername());
        try {
            if (rLock.tryLock()) {
                UserDO userDO = BeanUtil.toBean(requestParam, UserDO.class);
                try {
                    boolean save = save(userDO);
                    if(!save){
                        throw new ClientException(USER_REGISTER_ERROR);
                    }
                } catch (DuplicateKeyException e) {
                    throw new ClientException(USER_EXIST);
                }
                groupService.saveGroup(requestParam.getUsername(),"默认分组");
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                return;
            }
            throw new ClientException(USER_NAME_EXIST_ERROR);
        } finally {
            rLock.unlock();
        }
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + requestParam.getUsername());
        if(hasLogin!=null && hasLogin.equals(true)){
            throw new ClientException("用户已登录");
        }
        LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag,0);
        UserDO userDO = getOne(wrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForHash().put("login_"+requestParam.getUsername(),token, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_"+requestParam.getUsername(),30L, TimeUnit.DAYS);
        return UserLoginRespDTO.builder().token(token).build();
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username,token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if(!checkLogin(username,token)){
            throw new ClientException("用户Token不存在或未登录");
        }
        stringRedisTemplate.delete("login_"+username);
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        if(!UserContext.getUsername().equals(requestParam.getUsername())){
            throw new ClientException("不是当前登录用户，不能修改");
        }
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername,requestParam.getUsername());
        update(BeanUtil.toBean(requestParam, UserDO.class),updateWrapper);
    }
}
